package com.example.mybaiduweishi.receiver;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Message;

import com.example.mybaiduweishi.MyApplication;
import com.example.mybaiduweishi.R;
import com.example.mybaiduweishi.services.IVersionUpdate;
import com.example.mybaiduweishi.services.MyLoadNewVersionService;
import com.example.mybaiduweishi.utils.MyUtil;
import com.example.mybaiduweishi.vo.VersionInfo;
import com.socks.library.KLog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/5/22 0022.
 */

public class CheckUpdateBroadcast extends BroadcastReceiver {
    private int newversioncode;
    private int oldversioncode;
    private String des ="";

    private void showdialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(MyApplication.getContext());
        dialog.setIcon(R.drawable.baidu_guard)
                .setTitle("新版本"+newversioncode)
                .setMessage(des)
                .setPositiveButton("升级", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //1.隐藏对话框
                        dialog.dismiss();

                    }
                });
        dialog.show();

    }

    @Override
    // 接收广播
    public void onReceive(final Context context, Intent intent) {
        final Message message = Message.obtain();
        KLog.e("----------------","===准备更新====");
        SharedPreferences sharedPreferences = MyUtil.getSharedPre();
        //日期：datetime   比较上一次更新的时间，如果满了七天则再次提示更新(获取版本号)
        //使用retrofit2框架访问网络
        //前一次的日期(一个小字符串)用SharedPreferences共享首选项保存
        String olddate = sharedPreferences.getString("datetime", "2017-5-13");
        //此时的日期
        Date newdate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        simpleDateFormat.format(日期类);       //由日期类转成String类型
//        simpleDateFormat.parse(“”)
// 由String类转成日期类
        String dateformat = simpleDateFormat.format(newdate);

        try {
            Date checkdate =null;
            if (olddate != null){
                checkdate = simpleDateFormat.parse(olddate);
            }
            //日期差
            if (olddate == null || "".equals(olddate)){
                /**
                 *null则为第一次安装
                 * 将当前的日期存储在共享首选项
                 */
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("checkDate",dateformat);
                editor.commit();

            }else {
                int days = MyUtil.daysBetween(checkdate,newdate);
//                ToastUtil.showShortToast(context,days+"");

                if (days >= 7){
                    /**
                     * 访问服务器查看版本
                     * 将当前的日期存储在共享首选项
                     */
                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl("http://192.168.1.124:8080/")
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                    IVersionUpdate versionUpdate = retrofit.create(IVersionUpdate.class);  //创建接口对象
                    Call<VersionInfo> versionInfoCall = versionUpdate.getVersion();
                    versionInfoCall.enqueue(new Callback<VersionInfo>() {
                        @Override
                        public void onResponse(Call<VersionInfo> call, Response<VersionInfo> response) {
                            VersionInfo versionInfo = response.body();
                            //服务器上的版本
                            newversioncode = versionInfo.getVersioncode();
                            //正在使用的版本
                            oldversioncode = MyUtil.getVersionCode(MyApplication.getContext());

                            if (newversioncode > oldversioncode){
                                //进行强制更新
                                if (versionInfo != null) {
                                    //强制更新
                                    Intent intent = new Intent();
                                    intent.setClass(MyApplication.getContext(), MyLoadNewVersionService.class);
                                    intent.putExtra("apkurl", versionInfo.getApkurl());
                                    MyApplication.getContext().startService(intent);
                                }
                            }

                        }

                        @Override
                        public void onFailure(Call<VersionInfo> call, Throwable t) {

                        }
                    });

                }else {

                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }finally {

        }
    }
}
